package com.tanglongan.designPattern.dp11_flyweight.demo02;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {

    private final List<Connection> pool;

    public ConnectionPool() {
        pool = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < 20; i++) {
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root123");
                pool.add(connection);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }


    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        }
        return null;
    }

    public synchronized void release(Connection conn) {
        pool.add(conn);
    }

}
